<template>
    <div class="login-log-container">
        <!-- 表单搜索项 -->
        <el-form :model="params">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="登录地址" class="bold-label">
                        <el-input v-model="params.ipAddr" placeholder="请输入登录地址" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="用户名称" class="bold-label">
                        <el-input v-model="params.username" placeholder="请输入用户名称" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="状态" class="bold-label">
                        <el-select v-model="params.status" placeholder="登录状态" @change="handleStatusChange">
                            <el-option label="成功" value="0" />
                            <el-option label="失败" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter=10>
                <el-col :span="4">
                    <el-form-item label="登录时间" class="bold-label">
                        <el-date-picker v-model="params.start" type="date" placeholder="开始日期" />
                    </el-form-item>
                </el-col>
                <el-col :span="0.5" class="dividing-line">
                    <span>☺</span>
                </el-col>
                <el-col :span="3">
                    <el-form-item>
                        <el-date-picker v-model="params.over" placeholder="结束日期" style="width: 95%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                    <el-button type="primary" plain :icon="Refresh" @click="handleReset">重置</el-button>
                </el-col>
            </el-row>
        </el-form>
        <!-- 按钮组 -->
        <el-row class="button-group">
            <el-col :span="10">
                <div>
                    <el-button type="danger" plain :disabled="deleteDisabled" :icon="Delete"
                        @click="handleDelete">删除</el-button>
                    <el-button type="danger" plain :icon="Delete" @click="clearAll">清空</el-button>
                    <el-button type="warning" plain :icon="Download" @click="handleExport">导出</el-button>


                </div>
            </el-col>
            <el-col :span="14">
                <div class="button-right">
                    <el-tooltip content="隐藏搜索" placement="top">
                        <el-button :icon="Search" circle />
                    </el-tooltip>
                    <el-tooltip content="刷新" placement="top">
                        <el-button :icon="Refresh" circle />
                    </el-tooltip>
                </div>
            </el-col>
        </el-row>
        <!-- 数据表格 -->
        <el-row>
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" :selectable="selectable" width="40" />
                <el-table-column prop="logId" label="访问编号" align="center" />
                <el-table-column prop="userName" label="用户名称" sortable align="center" />
                <el-table-column prop="ipAddr" label="登录地址" align="center" />
                <el-table-column prop="loginLocation" label="登录地点" align="center" />
                <el-table-column prop="browser" label="浏览器" align="center" />
                <el-table-column prop="os" label="操作系统" align="center" />
                <el-table-column prop="status" label="登录状态" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
                            {{ scope.row.status === '0' ? '成功' : '失败' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="msg" label="操作信息" align="center" />
                <el-table-column prop="loginTime" label="登录日期" sortable align="center" width="180" />
            </el-table>
        </el-row>
        <!-- 分页组件 -->
        <el-row>
            <el-col :span="24">
                <div class="demo-pagination-block">
                    <el-pagination :current-page="params.currentPage" :page-size="params.pageSize" background
                        :default-page-size="params.pageSize" :page-sizes="pageSizes"
                        layout="total,sizes,prev,pager,next,jumper" :total="parseInt(pageResult.total)"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import { deleteLoginLog, getLoginLogList } from '@/apis/zs/index'
import { onMounted, ref } from 'vue';
import { Search, Refresh, Delete, Download } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
let ids = ref([]) // 选中行的id数组
const tableData = ref([])   // 表格数据
const pageResult = ref({}) // 分页数据
const deleteDisabled = ref(true) // 删除按钮禁用状态,默认禁用
const href = ref('') // 导出文件地址
// 搜索参数
const params = ref({
    currentPage: 1,
    pageSize: 2,
    ipAddr: '',
    username: '',
    status: '',
    start: '',
    over: ''
})
// 分页大小
const pageSizes = [2, 5, 8, 10]

onMounted(async () => {
    // 加载登录日志列表数据
    pageResult.value = await getLoginLogList(params.value)
    tableData.value = pageResult.value.records
})
/**
 * 更新状态
 * @param value 状态值
 */
const handleStatusChange = (value) => {
    params.value.status = value
}
/**
 * 处理搜索
 * @param params 搜索参数
 */
const handleSearch = async () => {
    pageResult.value = await getLoginLogList(params.value)
    tableData.value = pageResult.value.records
}
/**
 * 处理重置
 * @param params 搜索参数
 */
const handleReset = async () => {
    params.value = {
        currentPage: 1,
        pageSize: 2,
        ipAddr: '',
        username: '',
        status: '',
        start: '',
        over: ''
    }
    pageResult.value = await getLoginLogList(params.value)
    tableData.value = pageResult.value.records
}
/**
 * 处理分页大小变化
 * @param size 当前分页大小
 */
const handleSizeChange = async (size) => {
    params.value.pageSize = size
    pageResult.value = await getLoginLogList(params.value)
    tableData.value = pageResult.value.records
}
/**
 * 处理当前页码变化
 * @param currentPage 当前页码
 */
const handleCurrentChange = async (currentPage) => {
    params.value.currentPage = currentPage
    pageResult.value = await getLoginLogList(params.value)
    tableData.value = pageResult.value.records
}
/**
 * 自定义删除选中行的处理方法
 * @param row 行数据
 */
const selectable = (row) => {
    // 表示所有行数据都可以被选中，可以自定义选择逻辑
    return true
}
/**
 * 处理选中行变化
 * @param val 选中行的数组
 */
const handleSelectionChange = (val) => {
    deleteDisabled.value = !val.length
    ids.value = val.map(item => item.logId) // 使用map方法过滤出选中行的logId数组
}
/**
 * 处理删除选中行
 * @param ids 选中行的id数组
 */
const handleDelete = () => {
    ElMessageBox.confirm(`是否确认删除访问编号为${ids.value.join(',')}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        await deleteLoginLog(ids.value)
        pageResult.value = await getLoginLogList(params.value)
        tableData.value = pageResult.value.records
        ids.value = [] // 重置选中行的id数组
        ElMessage({ type: 'success', message: '删除成功' })
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' })
    })
}
/**
 * 处理清空所有数据项
 */
const clearAll = () => {
    ElMessageBox.confirm(`是否确认清空所有登录日志数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        await deleteLoginLog(ids.value)
        pageResult.value = await getLoginLogList(params.value)
        tableData.value = pageResult.value.records
        ids.value = [] // 重置选中行的id数组
        ElMessage({ type: 'success', message: '清空成功' })
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消清空' })
    })
}

// 导出文件
const handleExport = async () => {
    let disposition;
    fetch(`http://localhost:8081/api/loginLog/export?${new URLSearchParams(params.value).toString()}`, {
        method: 'GET',
        headers: {
            'Authorization': localStorage.getItem('token')
        }
    }).then(response => {
        disposition = response.headers.get('Content-Disposition')
        disposition = disposition.substring(disposition.indexOf('=') + 1)
        console.log(disposition)
        return response.blob()
    }).then(blob => {
        console.log(blob)
        const url = URL.createObjectURL(blob)
        href.value = url
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = href.value
        link.setAttribute('download', disposition)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
    })
}
</script>

<style scoped>
.dividing-line {
    text-align: center;
}

.button-right {
    text-align: right;
}

.button-group {
    margin-top: 20px;
    margin-bottom: 10px;
}

.demo-pagination-block .el-pagination {
    justify-content: end;
    margin-top: 20px;
}

.bold-label {
    font-weight: bold;
}
</style>
